package com.mexico.inloancash.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.google.gson.Gson;
import com.mexico.inloancash.R;
import com.mexico.inloancash.bean.India_User_Message_ListInfoBean;
import com.mexico.inloancash.bean.India_Version_ListBean;
import com.mexico.inloancash.http.IndiaRequestApi;
import com.mexico.inloancash.http.IndiaDKFactory;
import com.mexico.inloancash.utils.India_AdvertisingId_Clients;
import com.mexico.inloancash.utils.DeviceIdUtil;
import com.mexico.inloancash.utils.MyPreferencesManager;
import com.mexico.inloancash.utils.Utils;
import com.mexico.inloancash.utils.permission.RxPermissions;
import com.mexico.inloancash.utils.permission.SchedulerTransformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 加载页
 */
public class IndiaLaunchActivity extends BaseActivity {
    @BindView(R.id.until_time)
    TextView mUntil_Time;

    private CountDownTimer mUtils;
    private boolean isLocation = false;//权限获取
    private int time = 4;

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.india_sp_view_layout);
        ButterKnife.bind(this);
        setMy_Immersive();
        india_Load_GoogleId();
        EventBus.getDefault().register(this);
        getOutIP();
        mUtils = new CountDownTimer(4000, 1000) {
            @Override
            public void onTick(long l) {
                mUntil_Time.setClickable(false); //设置不可点击
                mUntil_Time.setText(l / 1000 + "s");  //设置倒计时时间
                time = (int) (l / 1000);
            }
            @Override
            public void onFinish() {
                time = 0;
                if (isLocation) {
                    Intent main = new Intent(IndiaLaunchActivity.this, MainActivity.class);
                    startActivity(main);
                    finish();
                }
            }
        };
        mUtils.start();
        india_Checkis_Or_Update();
        boolean isFirstComing = MyPreferencesManager.getIsFirstComing();
        if (isFirstComing) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(IndiaLaunchActivity.this, IndiaPermissionCheckActivity.class));
                }
            }, 2000);
        } else {
//            new RxPermissions(IndiaLaunchActivity.this)
//                    .request(Manifest.permission.ACCESS_COARSE_LOCATION,
//                            Manifest.permission.ACCESS_FINE_LOCATION,
//                            Manifest.permission.CAMERA,
//                            Manifest.permission.READ_PHONE_STATE,
//                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                            Manifest.permission.READ_CONTACTS,
//                            Manifest.permission.READ_SMS, //谷歌包要短信
//                            Manifest.permission.READ_CALL_LOG,
//                            Manifest.permission.READ_EXTERNAL_STORAGE)
//                    .compose(new SchedulerTransformer<>())
//                    .subscribe(aBoolean -> {
//                        if (aBoolean) {
//                            isLocation = true;
//                            if (time < 1) {
//                                Intent main = new Intent(IndiaLaunchActivity.this, MainActivity.class);
//                                startActivity(main);
//                                finish();
//                            }
//                        } else {
//                            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            //startActivity(intent);
//                            india_Jump_Setting();
//                        }
//                    });
            Intent main = new Intent(IndiaLaunchActivity.this, MainActivity.class);
            startActivity(main);
            finish();
        }
        MyPreferencesManager.putLast_login_time(System.currentTimeMillis());
    }


    //开启子线程获取外网ip地址
    private void getOutIP() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DeviceIdUtil.GetNetIp();
            }
        }).start();
    }

    protected void setMy_Immersive()
    {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)
        {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色透明
            window.setStatusBarColor(Color.TRANSPARENT);
            int visibility = window.getDecorView().getSystemUiVisibility();
            //布局内容全屏展示
            visibility |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            //隐藏虚拟导航栏
            //visibility |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            //防止内容区域大小发生变化
            visibility |= View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            window.getDecorView().setSystemUiVisibility(visibility);
        } else
        {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    @SuppressLint("CheckResult")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(India_User_Message_ListInfoBean event) {
        if (event.getCode() == 200) {

            Intent main = new Intent(IndiaLaunchActivity.this, MainActivity.class);
            startActivity(main);
            finish();

           MyPreferencesManager.isFirstComing(false);//刷新状态 不是第一次进来了
//
//            new RxPermissions(IndiaLaunchActivity.this)
//                    .request(
//                            Manifest.permission.ACCESS_COARSE_LOCATION,
//                            Manifest.permission.ACCESS_FINE_LOCATION,
//                            Manifest.permission.CAMERA,
//                            Manifest.permission.READ_PHONE_STATE,//不加这个权限 advance最新的sdk 会奔溃
//                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                            Manifest.permission.READ_CONTACTS,
//                            Manifest.permission.READ_SMS, //谷歌包要短信
//                            Manifest.permission.READ_CALL_LOG,
//                            Manifest.permission.READ_EXTERNAL_STORAGE)
//                    .compose(new SchedulerTransformer<>())
//                    .subscribe(aBoolean -> {
//                        if (aBoolean) {
//                            isLocation = true;
//                            if (time < 1) {
//                                Intent main = new Intent(IndiaLaunchActivity.this, MainActivity.class);
//                                startActivity(main);
//                                finish();
//                            }
//                        } else {
//                            //Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                            //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            //startActivity(intent);
//                            india_Jump_Setting();
//                        }
//                    });
        }
    }


    /**
     * 用户拒绝的权限 跳转至设置页面
     */
    private void india_Jump_Setting(){
        try {
            Intent intent = new Intent();
            intent.setAction(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
            Toast.makeText(this,"error",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 获取谷歌 GoogleAdvertisingId
     */
    private void india_Load_GoogleId() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final String id = India_AdvertisingId_Clients.getGoogleAdId(IndiaLaunchActivity.this);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (!TextUtils.isEmpty(id)) {
                                MyPreferencesManager.putGoogleID(id);
                                //Toast.makeText(Act_Loading.this,"保存成功"+MyPreferencesManager.getGoogleID(),Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    /**
     * 更新
     */
    public void india_Checkis_Or_Update() {
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> update = api.update("android");
        update.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    India_Version_ListBean bean = new Gson().fromJson(response.body(), India_Version_ListBean.class);
                    if (bean.getStatus() == 1) {
                        if (Utils.getVersionName(IndiaLaunchActivity.this).equals(Double.valueOf(bean.getData().getData().getVersion()))) {
                            getUpdate(bean.getData().getData().getApp_link());
                        } else {
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                //MyToast.show(SpActivity.this, "Silakan periksa jaringan");
            }
        });
    }


    public void getUpdate(final String url) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("更新提示");
        builder.setMessage("退出");
        builder.setNegativeButton("退出软件", (dialogInterface, i) -> finish());
        builder.setPositiveButton("开始更新", (dialogInterface, i) -> {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(url);
            intent.setData(content_url);
            startActivity(intent);
        });
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @OnClick(R.id.skip)
    public void onViewClicked() {
        if (isLocation) {
            Intent main = new Intent(IndiaLaunchActivity.this, MainActivity.class);
            startActivity(main);
            finish();
        }
    }

    /**
     * 统计app下载
     */
    public void india_CountDown() {
        String deviceId = DeviceIdUtil.getDeviceId(this);
        IndiaRequestApi api = IndiaDKFactory.getInstance().getApi();
        Call<String> getDown = api.statistics(deviceId, "test");
        getDown.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                MyPreferencesManager.getString("isFirstLoad", "isFirstLoad");
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    /**
     * 地址选择
     */
    /*public void publicaddress() {
        HttpHelper.publicaddress(new HttpHelper.HttpUtilsCallBack<String>() {
            @Override
            public void onFailure(String failure) {
                MyToast.show(context, failure);
                loding.dismiss();
            }

            @Override
            public void onSucceed(String succeed) {
                loding.dismiss();
                Gson gson = new Gson();
                publicaddressBean getSmsVerifyBean = gson.fromJson(succeed, publicaddressBean.class);
                if (getSmsVerifyBean.getStatus() == 1) {
                    JsonDataBean jsonDataBean = new JsonDataBean();
                    List<JsonDataBean.DataBean> shengfen = new ArrayList<>();
                    for (int i = 0; i < getSmsVerifyBean.getData().size(); i++) {
                        JsonDataBean.DataBean dataBean = new JsonDataBean.DataBean();
                        List<JsonDataBean.DataBean.CityBean> City = new ArrayList<>();
                        for (int j = 0; j < getSmsVerifyBean.getData().get(i).getRegencies().size(); j++) {
                            JsonDataBean.DataBean.CityBean bean = new JsonDataBean.DataBean.CityBean();
                            List<String> area = new ArrayList<>();
                            for (int f = 0; f < getSmsVerifyBean.getData().get(i).getRegencies().get(j).getDistricts().size(); f++) {
                                area.add(getSmsVerifyBean.getData().get(i).getRegencies().get(j).getDistricts().get(f).getName());
                            }
                            bean.setName(getSmsVerifyBean.getData().get(i).getRegencies().get(j).getName());
                            bean.setArea(area);
                            City.add(bean);
                        }
                        dataBean.setName(getSmsVerifyBean.getData().get(i).getName());
                        dataBean.setCity(City);
                        shengfen.add(dataBean);
                    }
                    jsonDataBean.setData(shengfen);
                    String datas = gson.toJson(jsonDataBean);
                    JSONObject jsonObject = null;
                    String data = "";
                    try {
                        jsonObject = new JSONObject(datas);
                        data = jsonObject.getString("data");
                        aCache.put("cityBean", data);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(String error) {
                loding.dismiss();
                MyToast.show(context, error);
            }
        });
    }*/
}
